package Utils;

import java.sql.Connection;
import java.sql.SQLException;

public class JDBCUtils {
    private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<>();

    public static Connection getConn() {
        Connection conn = connectionHolder.get();
        if (conn == null) {
            try {
                conn = DataSourceFactory.getDataSource().getConnection();
                connectionHolder.set(conn);
            } catch (SQLException e) {
                throw new RuntimeException("Failed to get database connection", e);
            }
        }
        return conn;
    }

    public static void closeConnection() {
        Connection conn = connectionHolder.get();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // log error
            } finally {
                connectionHolder.remove();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(JDBCUtils.getConn());
    }
}
